/*
author: dcj
create date: 2013-7-22
modify date: 2013-8-12
description: All the action on map will be defined in this file.
*/

import com.esri.ags.FeatureSet;
import com.esri.ags.Graphic;
import com.esri.ags.components.ContentNavigator;
import com.esri.ags.events.AttributeInspectorEvent;
import com.esri.ags.events.DrawEvent;
import com.esri.ags.events.GraphicEvent;
import com.esri.ags.events.MapMouseEvent;
import com.esri.ags.events.RouteEvent;
import com.esri.ags.geometry.Extent;
import com.esri.ags.geometry.Geometry;
import com.esri.ags.geometry.MapPoint;
import com.esri.ags.symbols.CompositeSymbol;
import com.esri.ags.symbols.SimpleLineSymbol;
import com.esri.ags.symbols.SimpleMarkerSymbol;
import com.esri.ags.symbols.Symbol;
import com.esri.ags.symbols.TextSymbol;
import com.esri.ags.tasks.QueryTask;
import com.esri.ags.tasks.supportClasses.IdentifyParameters;
import com.esri.ags.tasks.supportClasses.IdentifyResult;
import com.esri.ags.tasks.supportClasses.Query;
import com.esri.ags.tasks.supportClasses.RouteResult;
import com.esri.ags.tools.DrawTool;
import com.esri.ags.utils.GraphicUtil;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.text.TextFormat;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.events.IndexChangedEvent;
import mx.resources.IResourceBundle;
import mx.resources.IResourceManager;
import mx.resources.ResourceBundle;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import mx.rpc.events.FaultEvent;

import spark.components.DropDownList;
import spark.events.IndexChangeEvent;

private function pMap_loadHandler():void{
	pMap.addEventListener(MouseEvent.MOUSE_MOVE,pMap_onMouseMoveHandler);
	pMap.addEventListener(MapMouseEvent.MAP_CLICK,pMap_onMapClickHandler);
	pMap.addEventListener(MouseEvent.MOUSE_WHEEL,pMap_onMouseWheelHandler);
	pMap.infoWindow.addEventListener(Event.CLOSE,pMap_infoWindow_CloseHandler);
	enableSelectByExtent();
	pFeatureLayer.visible=false;
}

private function pMap_onMouseMoveHandler(event:MouseEvent):void{
	const mapPoint:MapPoint = pMap.toMapFromStage(event.stageX,event.stageY);
	mapCoordinate.text = mapPoint.x.toFixed(1)+","+mapPoint.y.toFixed(1);
}

private function pMap_onMapClickHandler(event:MapMouseEvent):void{
	queryGraphicsLayer.clear();
	pMap_IdentityHandler(event.mapPoint);
}

private function pMap_onMouseWheelHandler(event:MouseEvent):void{
	enableSelectByExtent();
}

private function pMap_extentChangeHandler():void{
	enableSelectByExtent();
}

private function enableSelectByExtent():void{
	if(pMap.scale <= 4000){
		chkSelectByExtent.enabled = true;
	} else {
		chkSelectByExtent.enabled = false;
	}
	
	if(pMap.scale < conf.ZoomScale.Min){
		pMap.scale = conf.ZoomScale.Min;
	}
	
	if(pMap.scale > conf.ZoomScale.Max){
		pMap.scale = conf.ZoomScale.Max;
	}
}

private function pMap_IdentityHandler(clickPoint:MapPoint):void{
	var identifyParams:IdentifyParameters = new IdentifyParameters();
	identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_VISIBLE;
	identifyParams.layerIds = [0,1]; // The layers to perform the Identify operation on. The ID is returned in layerInfos. Only applies when layerOption is "all" or "visible". 
	identifyParams.returnGeometry = true;
	identifyParams.tolerance = 5;
	identifyParams.width = pMap.width;
	identifyParams.height = pMap.height;
	identifyParams.mapExtent = pMap.extent;
	identifyParams.spatialReference = pMap.spatialReference;
	identifyParams.geometry = clickPoint;
	
	identifyTask.execute(identifyParams,new AsyncResponder(result_identityTask,fault_identityTask));
	
	function result_identityTask(results:Array,token:Object = null):void{
		highlightGraphicsLayer.clear();
		
		var count:int = results.length;
		if(results && count>0){
			var infoPoint:MapPoint = results[0].feature.geometry;
			
			for(var i:int = 0;i<count;i++){
				var result:IdentifyResult = results[i];
				var pGraphic:Graphic = result.feature;
				pMap_infoWindow_setContentHandler(pGraphic); // 设定信息窗口的显示字段
				highlightGraphicsLayer.add(new Graphic(result.feature.geometry,onSelectionMarker));
				break;
			}
			pMap.infoWindow.show(infoPoint);
		} else {
			//Alert.show("该图层不可查询！");
		}
	}
	
	function pMap_infoWindow_setContentHandler(graphic:Graphic):void{
		iwContent.LNG = graphic.attributes.X坐标;
		iwContent.LAT = graphic.attributes.Y坐标;
		iwContent.LOCATION = graphic.attributes.位置编号;
		iwContent.STATUS = graphic.attributes.状态;
		iwContent.TYPES = graphic.attributes.灯具类别;
		iwContent.LAMPTYPE = graphic.attributes.灯具类型;
		iwContent.LAMPID = graphic.attributes.灯具编号;
		iwContent.BOXID = graphic.attributes.灯箱编号;
		iwContent.LIGHTID = graphic.attributes.lightid;
		iwContent.REPAIR = graphic.attributes.维修人员;
		iwContent.RECORDER = graphic.attributes.记录人员;
		iwContent.DATE = graphic.attributes.维修日期;
	}
	
	function fault_identityTask(error:Object,token:Object = null):void{
		Alert.show(String(error),"Identity Error");
	}
}

private function pMap_infoWindow_CloseHandler(event:Event):void{
	highlightGraphicsLayer.clear();
	queryGraphicsLayer.clear();
	//pFeatureLayer.clearSelection();
}

private function mapDrawTool_drawEndHandler(event:DrawEvent):void{
	mapDrawTool.deactivate();
	if(event.graphic.geometry is Extent){
		var symbol:SimpleMarkerSymbol = new SimpleMarkerSymbol();
		symbol.alpha = 20;
		symbol.size = 6;
		symbol.color = 0xFF5500;
		symbol.outline = new SimpleLineSymbol();
		
		ExecuteQuery(null,symbol,event.graphic.geometry);
		
		chkSelectByExtent.selected = false;
	} else {
		pFeatureLayer.visible = false;
	}
}

private function pFeatureLayer_faultHandler(event:FaultEvent):void{
	pFeatureLayer.visible = false;
	Alert.show(event.fault.faultString + "\n\n" + event.fault.faultDetail, "FeatureLayer error " + event.fault.faultCode);
}

private function getFeatureCount(value:Array):int{
	return value.length;
}

private function attributeInspector_showFeatureHandler(event:AttributeInspectorEvent):void{
	highlightGraphicsLayer.clear();
	var g:Graphic = new Graphic(event.feature.geometry);
	g.symbol = onSelectionMarker;
	highlightGraphicsLayer.add(g);
}

private function chkSelectByExtent_changeHandler():void{
	//Alert.show(chkSelectByExtent.selected.toString());
	
	if(chkSelectByExtent.selected){
		// 激活拉框查询
		mapDrawTool.activate(DrawTool.EXTENT);
		mapDrawTool.showDrawTips = true;
		pFeatureLayer.visible = true;
	} else {
		mapDrawTool.deactivate();
		highlightGraphicsLayer.clear();
		queryGraphicsLayer.clear();
		pFeatureLayer.clearSelection();
		pFeatureLayer.visible = false;
	}
}

private function btnFullExtent_clickHandler():void{
	var fullExtent:Extent = new Extent();
	fullExtent.spatialReference = mapSR;
	fullExtent.xmin = conf.FullExtent.Xmin;
	fullExtent.ymin = conf.FullExtent.Ymin;
	fullExtent.xmax = conf.FullExtent.Xmax;
	fullExtent.ymax = conf.FullExtent.Ymax;
	pMap.extent = fullExtent;
}

private function ddlSelectLampType_initializeHandler():void{
	var typeArray:ArrayCollection = new ArrayCollection();
	var lampTypeCount:int = conf.LampTypes.Type.length;
	for (var i:int=0;i<lampTypeCount;i++){
		typeArray.addItem(conf.LampTypes.Type[i].name);
	}
	
	ddlSelectLampType.dataProvider = typeArray;
	ddlSelectLampType.selectedIndex = 0;
}

private function ddlSelectLampType_changeHandler():void{
	var lampTypeId:int = ddlSelectLampType.selectedIndex;
	if(lampTypeId!=0){
		pFeatureLayer.visible = true;
		
		var lampType:String = ddlSelectLampType.selectedItem;
		//var whereClause:String = "types = '"+lampType + "'";
		var whereClause:String = "sde.sde.lamp_location.types = '"+lampType + "'";
		var symbol:SimpleMarkerSymbol = new SimpleMarkerSymbol();
		symbol.alpha = 20;
		symbol.size = 8;
		symbol.color = conf.LampTypes.Type[lampTypeId].color;
		symbol.outline = new SimpleLineSymbol();
		
		ExecuteQuery(whereClause,symbol);
	} else {
		//Alert.show("显示所有灯");
		highlightGraphicsLayer.clear();
		queryGraphicsLayer.clear();
		pFeatureLayer.clearSelection();
		pFeatureLayer.visible = false;
	}
}

private function ExecuteQuery(whereClause:String,symbol:Symbol,pGeometry:Geometry=null):void{
	query.where = whereClause;
	query.geometry = pGeometry;
	pFeatureLayer.selectFeatures(query);
	//Alert.show(pFeatureLayer.selectedFeatures.length.toString());
	queryGraphicsLayer.clear();
	queryGraphicsLayer.symbol = symbol;
	
	var queryTask:QueryTask = new QueryTask(conf.PDZHDFeatureLayer);
	queryTask.showBusyCursor = true;
	queryTask.execute(query,new AsyncResponder(onResult,onFault));
	
	function onResult(pFeatureSet:FeatureSet,token:Object=null):void{
		var selectionCount:int = pFeatureSet.features.length;
		if(selectionCount == 1){
			var pGeometry:Geometry = pFeatureSet.features[0].geometry;
			if(pGeometry.type == Geometry.MAPPOINT){
				var graphic:Graphic = new Graphic(pGeometry);
				var margin:int = 50;
				minExtent.xmax = graphic.x + margin;
				minExtent.xmin = graphic.x - margin;
				minExtent.ymax = graphic.y + margin;
				minExtent.ymin = graphic.y - margin;
				pMap.extent = minExtent;
				
				pMap_IdentityHandler(pGeometry as MapPoint); // 对唯一的一个查询结果，自动显示 infoWindow
			}
			pMap.zoomTo(pGeometry);
			queryGraphicsLayer.add(pFeatureSet.features[0]);
		} else if(selectionCount > 1){
			var graphicsExtent:Extent = GraphicUtil.getGraphicsExtent(pFeatureSet.features);
			if(graphicsExtent){
				var buffer:int = 50;
				graphicsExtent.xmin-=buffer;
				graphicsExtent.xmax+=buffer;
				graphicsExtent.ymin-=buffer;
				graphicsExtent.ymax+=buffer;
				pMap.extent = graphicsExtent;
			}
			
			for(var i:int=0;i<selectionCount;i++){
				queryGraphicsLayer.add(pFeatureSet.features[i]);
			}
		} else {
			if(whereClause!=conf.FaultLamp.Clause){
				Alert.show("查无此灯！","提示");
			} else {
				Alert.show("设备运行良好，没有故障！","提示");
			}
		}
	}
	
	function onFault(info:Object,token:Object=null):void{
		Alert.show(info.toString(),"查询错误");
	}
}

private function btnClearSelection_clickHandler():void{
	queryGraphicsLayer.clear();
	highlightGraphicsLayer.clear();
	pFeatureLayer.clearSelection();
	pFeatureLayer.visible = false;
	ddlSelectLampType.selectedIndex = 0;
	if(chkSelectByExtent.selected){
		mapDrawTool.deactivate();
		chkSelectByExtent.selected = false;
	}
}

private function txtLocalID_keyDownHandler(event:KeyboardEvent):void{
	if(event.keyCode == 13){
		// 输入回车键，确认
		//var whereClause:String = "localid = '"+ txtLocalID.text.toLocaleUpperCase() +"'";
		var whereClause:String = "sde.sde.lamp_location.location = '"+ txtLocalID.text.toLocaleUpperCase() +"'";
		var symbol:SimpleMarkerSymbol = new SimpleMarkerSymbol();
		symbol.alpha = 20;
		symbol.size = 8;
		symbol.color = 0xFF5500;
		symbol.outline = new SimpleLineSymbol();
		
		ExecuteQuery(whereClause,symbol);
	}
}

private function txtLocalID_focusOutHandler():void{
	txtLocalID.text = "请输入灯座位置号(Localid)";
}

private function txtLocalID_focusInHandler():void{
	txtLocalID.text = "";
}

private function btnGetFaultLamp_ClickHandle():void{
	//Alert.show("btnGetFaultLamp_ClickHandle()");
	pFeatureLayer.visible = true;
	
	var whereClause:String = conf.FaultLamp.Clause;
	var symbol:SimpleMarkerSymbol = new SimpleMarkerSymbol();
	symbol.alpha = 20;
	symbol.size = 8;
	symbol.color = conf.FaultLamp.Color;
	symbol.outline = new SimpleLineSymbol();
	
	ExecuteQuery(whereClause,symbol);
}

private function creationCompleteHandler():void{
	var resourceManager:IResourceManager = ResourceManager.getInstance();
	var pResourceBundle:IResourceBundle = resourceManager.getResourceBundle("en_US","ESRIMessages") as IResourceBundle;
	pResourceBundle.content["drawTooltipOther"] = "单击并拖动鼠标";
	//pResourceBundle.content["scaleBarMeters"] = "米";
	//pResourceBundle.content["scaleBarFeet"] = "英尺";
}

private function ddlSelectRegionID_initializeHandler():void{
	
}

private function ddlSelectRegionID_changeHandler():void{
	
}


private var lastRoute:Graphic;
private var stopCount:int = 0;
protected function chkRouting_changeHandler(event:Event):void
{
	// TODO Auto-generated method stub
	if(chkRouting.selected){
		pMap.removeEventListener(MapMouseEvent.MAP_CLICK,pMap_onMapClickHandler);
		pMap.addEventListener(MapMouseEvent.MAP_CLICK,pMap_Routing_onMapClickHandle);
	} else {
		clearRouteStatus();
		pMap.removeEventListener(MapMouseEvent.MAP_CLICK,pMap_Routing_onMapClickHandle);
		pMap.addEventListener(MapMouseEvent.MAP_CLICK,pMap_onMapClickHandler);
	}
}

protected function routeTask_faultHandler(event:FaultEvent):void
{
	// TODO Auto-generated method stub
	Alert.show(event.fault.faultString + "\n" + event.fault.faultDetail,"Routing Error " + event.fault.faultCode);
	
	if(stops.features.length <=2){
		pMap.defaultGraphicsLayer.clear();
	} else {
		pMap.defaultGraphicsLayer.remove(stops.features.pop());
	}
}

protected function routeTask_solveCompleteHandler(event:RouteEvent):void
{
	// TODO Auto-generated method stub
	var routeResult:RouteResult = event.routeSolveResult.routeResults[0];
	routeResult.route.symbol = routeSymbol;
	pMap.defaultGraphicsLayer.remove(lastRoute);
	lastRoute = routeResult.route;
	lastRoute.toolTip = routeResult.routeName;
	
	pMap.defaultGraphicsLayer.add(lastRoute);
}

protected function pMap_Routing_onMapClickHandle(event:MapMouseEvent):void{
	stopCount++;
	var stopName:String = "Stop "+stopCount;
	var stopSymbol:CompositeSymbol = new CompositeSymbol();
	var circleSym:SimpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE,20,0x000099);
	var textSym:TextSymbol = new TextSymbol(String(stops.features.length+1));
	textSym.textFormat = new TextFormat("Verdana",null,null,true);
	textSym.color = 0xFFFFFF;
	stopSymbol.symbols = [circleSym,textSym];
	var stop:Graphic = new Graphic(event.mapPoint,stopSymbol,{name:stopName});
	stop.toolTip = stopName;
	pMap.defaultGraphicsLayer.add(stop);
	
	stops.features.push(stop);
	if(stops.features.length >1){
		routeParams.outSpatialReference = pMap.spatialReference;
		routeTask.solve(routeParams);
	}
}

private function clearRouteStatus():void{
	pMap.defaultGraphicsLayer.clear();
	stops.features = new Array();
}















